import Vue from 'vue';
import Vuex from 'vuex';
import {bindUid} from '@/utils/http'
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		app_config: null,
		user_info: null,
		user_agent:null, //应用适配场景：浙里办APP、支付宝-浙里办小程序。
		server_timestamp:'',//设置服务器时间
		session_id: null,//会话窗口ID
		//url: socketurl(),
		socketTask: null,//全局socket
		is_open_socket: false,
		client_id: '',
		error_msg: [], // 发送失败的消息
		max_retry_count: 3, // 最大重连次数
		current_retry_count: 0,
		page_hide_close_ws: true, // 是否在页面hide时关闭链接，兼容预览图片的情况
		unload_close_ws: false, // ws关闭状态码兼容性不好，手动标记页面卸载关闭ws链接
		errorTips: '',
		timer: '',
		record_msg: [],
		leave_msg: [],//离线消息

	},
	mutations: {
		fn_set_app_config: (state, param) => {
			const obj = state;
			obj.app_config = param
		},
		fn_set_user_info: (state, param) => {
			const obj = state;
			obj.user_info = param
		},
		fn_set_server_timestamp:(state, param) => {
			const obj = state;
			obj.server_timestamp = param
		},
		fn_set_user_agent: (state, param) => {
			const obj = state;
			obj.user_agent = param
		},
		//设置会话窗口
		set_session_id: (state, session_id) => {
			const obj = state;
			obj.session_id = session_id
		},
		//设置聊天记录
		set_record_msg: (state, res) => {
			let session_id = res.session_id
			let msgs = res.data;
			msgs.sort(function (a, b) {
				return a['id'] - b['id']
			})

			if (res.current_page == 1) {
				state.record_msg[session_id] = msgs
			} else {
				state.record_msg[session_id] = [...state.record_msg[session_id], ...msgs]
			}
			// obj.msg_list = param
		},
		init: (state, msg) => {
			if (state.user_info && state.client_id != msg.client_id) {
				console.log('监听消息' + msg.client_id);
				state.client_id = msg.client_id
				bindUid()
			}
			state.client_id = msg.client_id
			// console.log(param.client_id);
			// const obj = state;
			// obj.user_info = param
		},
		chat_record: (state, msg) => {
			if (state.session_id != msg.session_id) {
				// // console.log('当前' + state.session_id, '消息session_id' + msg.session_id);
				// state.leave_msg.push(msg);
				// if(state.leave_msg[msg.session_id]){
				// 	// state.leave_msg[msg.session_id] = [...state.leave_msg[msg.session_id], ...msg];
				// }else{
					
				// }
				state.leave_msg= [];
				state.leave_msg[msg.session_id] = msg;
				console.log(state.leave_msg);
				//state.leave_msg = [...state.leave_msg, ...msg];
			}
		},
		//清除数据
		clear_session_record: (state, session_id) => {
			console.log(state);
			const obj = state;
			if(obj.leave_msg){
				if( obj.leave_msg[session_id]){
					obj.leave_msg.splice(session_id,1);
				}
			}else{
				obj.leave_msg = [];
			}
			console.log(obj.leave_msg);
		},
		reset_max_reter_count: (state) => {
			state.max_retry_count = 3;
			state.current_retry_count = 0;
		},
		fn_socket_init: (state, url) => {
			//const obj = state;
			state.socketTask = uni.connectSocket({
				url: url,
				header: {
					'content-type': 'application/json'
				},
				// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
				success(data) {
					console.log("websocket连接成功");
				},
			});

			// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
			state.socketTask.onOpen((res) => {
				console.log("WebSocket连接正常打开中...！");
				state.is_open_socket = true;
				state.current_retry_count = 0
				const error_msg = state.error_msg;
				for (let i in state.error_msg) {
					store.commit('fn_socket_send', state.error_msg[i]);
				}
				state.error_msg = [];
				state.errorTips = '';

				if (state.timer != null) {
					clearInterval(state.timer)
				}
				state.timer = setInterval(() => {
					store.commit('fn_socket_send');
				}, 28000);

				// 注：只有连接正常打开中 ，才能正常收到消息
				// state.socketTask.onMessage((res) => {
				// 	let msg = JSON.parse(res.data)
				// 	try {
				// 		if (typeof store._mutations[msg.type] !== 'undefined') {
				// 			store.commit(msg.type, msg);
				// 		}
				// 	} catch (error) {
				// 		console.log(error.msg);
				// 	}
				// });
				uni.onSocketMessage((res) => {
					let msg = JSON.parse(res.data)
					try {
						if (typeof store._mutations[msg.type] !== 'undefined') {
							store.commit(msg.type, msg);
						}
					} catch (error) {
						console.log(error.msg);
					}
				});
				
			})
			// 链接打开
			// uni.onSocketOpen(function (res) {
			// 	console.log('链接已打开')
			// 	state.is_open_socket = true;
			// 	state.current_retry_count = 0
			// 	// 重新发送所有出错的消息
			// 	const error_msg = state.error_msg;
			// 	for (let i in state.error_msg) {
			// 		store.commit('fn_socket_send', state.error_msg[i]);
			// 	}
			// 	state.error_msg = [];
			// 	state.errorTips = '';

			// 	if (state.timer != null) {
			// 		clearInterval(state.timer)
			// 	}
			// 	state.timer = setInterval(() => {
			// 		store.commit('fn_socket_send');
			// 	}, 28000);

			// })

			// // 收到消息
			// uni.onSocketMessage(function (res) {

			// 	let msg = JSON.parse(res.data)
			// 	let type = msg.type;
			// 	console.log(msg.type);
			// 	console.log(store._mutations[type]);

			// 	try {
			// 		if (store._mutations[msg.type]) {
			// 			store.commit(msg.type, msg);
			// 		}
			// 	} catch (error) {
			// 		console.log(error.msg);

			// 	}

			// })

			// 出错
			uni.onSocketError(function (res) {
				state.is_open_socket = false
				state.errorTips = 'WebSocket 发生错误!'
				console.log('链接出错', res)
			})

			// 链接关闭
			uni.onSocketClose(function (res) {
				// 工具上是1000，真机上测试是10000
				console.log('链接已关闭', res)
				state.is_open_socket = false

				if (state.timer != null) {
					clearInterval(state.timer)
				}

				if (state.errorTips.indexOf('重连') === -1) {
					state.errorTips = '网络链接已断开!'
				}

				if (
					res.code == 1000 ||
					res.code == 10000 ||
					state.unload_close_ws
				) {
					return
				}

				if (state.max_retry_count) {
					//发起重连
					state.timer = setInterval(() => {
						store.commit('retry_websocket');
					}, 3000);

				}
			})

		},
		// 重连ws
		retry_websocket(state,url) {
			var that = this
			if (state.current_retry_count < state.max_retry_count) {
				state.current_retry_count++;
				store.commit('fn_socket_init',url)
				state.errorTips = '重连WebSocket第' + state.current_retry_count + '次';
			} else {
				if (state.timer != null) {
					clearInterval(state.timer);
				}

				state.errorTips = '每隔10秒将再次尝试重连 WebSocket';
				state.timer = setInterval(() => {
					store.commit('fn_socket_init',url);
				}, 10000);//每10秒重新连接一次
			}
		},
		fn_socket_send(state, message) {
			if (!message) {
				message = {
					message: 'Message',
					type: 'ping'
				}
			}
			// const client_id = this.client_id
			message = Object.assign(message, { client_id: state.client_id })

			if (state.socketTask && state.is_open_socket) {
				uni.sendSocketMessage({
					data: JSON.stringify(message)
				})
			} else {
				console.log(
					'消息发送出错',
					message,
					state.socketTask,
					state.is_open_socket
				)
				state.error_msg.push(message)
			}
			//console.log("ws发送！");
			// state.socketTask.send({
			// 	data: p,
			// 	async success() {
			// 		//console.log("消息发送成功");
			// 	},
			// });
		},
		close_websocket(state) {
			state.socketTask.close()
		},
	},
	getters: {},
	actions: {
		fn_set_app_config({ commit }, param) { commit('fn_set_app_config', param) },
		fn_set_user_agent({ commit }, param) { commit('fn_set_user_agent', param) },
		fn_socket_init({ commit }, url) { commit('fn_socket_init', url) },
		fn_socket_send({ commit }, p) { commit('fn_socket_init', p) },
		set_session_id({ commit }, session_id) { commit('set_session_id', session_id) },
	}

})
//设置store数据永久保存
if (uni.getStorageSync('state')) {
	store.replaceState(JSON.parse(uni.getStorageSync('state')))
}
store.subscribe((mutation, state) => {
	// console.log( JSON.stringify(state) )  
	uni.setStorageSync('state', JSON.stringify(store.state));
})
export default store;